package cn.lijiguo.concurrency.part1.ch06;

import java.util.concurrent.TimeUnit;

/**
 * WrongWayVolatile
 * 演示使用 volatile 关键字的局限性：part 1 看似可行
 * @author lijiguo
 * @date 2020/1/6 13:32
 */
public class WrongWayVolatile implements Runnable {

    private volatile boolean canceled = false;

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatile r = new WrongWayVolatile();

        Thread wrong = new Thread(r, "wrong");
        wrong.start();

        TimeUnit.SECONDS.sleep(5);

        // 将标志位设置为 true 停止线程
        r.setCanceled(true);
    }

    @Override
    public void run() {
        int num = 0;
        try {
            while(num <= 10000 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + " 是 100 的倍数");
                }

                num++;

                Thread.sleep(10);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public boolean isCanceled() {
        return canceled;
    }

    public void setCanceled(boolean canceled) {
        this.canceled = canceled;
    }
}
